import os
import Image

import mimetypes

from damn.util import GetScriptPath, RunBlenderURI, ParseOptionsMap, AssetPathAbsolute, BlenderDependency

from damn.transcoder import TranscoderFailedException, BaseTranscoder

BlenderDependency()

class BlenderMeshPreviewTranscoder(BaseTranscoder):
  transcoder = True
  convert_map = {"application/x-blender.object" : ["image/jpeg", "image/png"]}
  _options = [('sizex', int, 512), 
              ('sizey', int, 512), 
              ('angley', float, 0.0), 
              ('cameraType', str, 'PERSP'), 
              ('cameraAngley', float, 0.0),]
  options_map = {"application/x-blender.object" : _options}

  def transcode(self, anAssetReference, dstFormat, **kwargs): 
    filePath = super(BlenderMeshPreviewTranscoder, self).transcode(anAssetReference, dstFormat, kwargs)
    
    tempfilePath = anAssetReference.file.fileName
    count = 1
    while count > -1:
      environ = {}
      environ["BlenderImageTranscoder-sizex"] = str(kwargs['sizex'])
      environ["BlenderImageTranscoder-sizey"] = str(kwargs['sizey'])
      
      environ["BlenderImageTranscoder-angley"] = str(kwargs['angley'])
      environ["BlenderImageTranscoder-cameraType"] = str(kwargs['cameraType'])
      environ["BlenderImageTranscoder-cameraAngley"] = str(kwargs['cameraAngley'])
      
      environ["BlenderImageTranscoder-object"] = anAssetReference.subName
      environ["BlenderImageTranscoder-path"] = filePath
      
      # Blender supported formats
      # (, 'BMP', 'IRIS', 'PNG', 'JPEG', 'JPEG2000', 'TARGA', 'TARGA_RAW', 
      #'CINEON', 'DPX', 'MULTILAYER', 'OPEN_EXR', 'HDR', 'TIFF', 'AVI_JPEG', 'AVI_RAW', 'FRAMESERVER', 'H264', 'FFMPEG', 'THEORA', 'XVID')
      environ["BlenderImageTranscoder-format"] = {'image/jpeg':'JPEG', 'image/png':'PNG'}.get(dstFormat, 'PNG')
      
      dependencies={}
      for asset in anAssetReference.dependencies:
        if asset.format not in dependencies: dependencies[asset.format] = {}
        dependencies[asset.format][asset.subName] = (str(asset.id), asset.file.fileName,)
      environ["BlenderImageTranscoder-dependencies"] = repr(dependencies)
      
      stdoutdata, stderrdata, returncode = RunBlenderURI(tempfilePath, GetScriptPath(__file__), None, environ)
      
      if count > 0 and returncode != 0:
        print '-'*70
        print 'An error occured: (assuming old blender file bug, saving in 2.5 and retrying once)'
        print '-'*70
        
        environ["BlenderImageTranscoder-filePath"] = anAssetReference.file.fileName
        
        environ["BlenderImageTranscoder-typeName"] = 'mesh'
        environ["BlenderImageTranscoder-object"] = anAssetReference.subName
        
        from assets.urls import default_path
        tempfilePath = os.path.join(default_path(), 'tmp', str(anAssetReference.id), anAssetReference.subName+'.blend')
        environ["BlenderImageTranscoder-tempfilePath"] = tempfilePath
        
        stdoutdata, stderrdata, returncode = RunBlenderURI('', GetScriptPath(__file__, '2.5convert'), None, environ)
        
        if returncode != 0: raise TranscoderFailedException('BlenderMeshPreviewTranscoder failed in first pass!')
      elif returncode != 0:
        if not returncode == -11: #TODO: this is prolly BAD, but it seems to render even though it crashes afterwards :s
          print('BlenderMeshPreviewTranscoder failed in second pass (return code %d)!'%(returncode))
          raise TranscoderFailedException('BlenderMeshPreviewTranscoder failed in second pass (return code %d)!'%(returncode))
      
      count = count -1
    
    return filePath 
      
    
